package net.luoran.dvm.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.luoran.dvm.common.base.PageFactory;
import net.luoran.dvm.common.base.Result;
import net.luoran.dvm.common.util.FileUtil;
import net.luoran.dvm.entity.PanelDO;
import net.luoran.dvm.entity.PanelGroupDO;
import net.luoran.dvm.entity.PanelModuleDO;
import net.luoran.dvm.entity.SysFileDO;
import net.luoran.dvm.entity.dto.PanelDTO;
import net.luoran.dvm.entity.dto.PanelGroupDTO;
import net.luoran.dvm.service.PanelGroupService;
import net.luoran.dvm.service.PanelModuleService;
import net.luoran.dvm.service.PanelService;
import net.luoran.dvm.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据大屏组 前端控制器
 * </p>
 *
 * @author MyBatisPlusGenerater
 * @since 2020-10-29
 */
@Controller
@RequestMapping("/panel")
public class PanelGroupController {

    @Value("${upload.file.path}")
    public String basePath;

    @Value("${server.servlet.context-path}")
    public String contextPath;

    @Autowired
    private PanelGroupService panelGroupService;

    @Autowired
    private PanelService panelService;

    @Autowired
    private PanelModuleService panelModuleService;

    @Autowired
    private SysFileService sysFileService;

    @GetMapping
    public String panelMain(Model model) {
        model.addAttribute("contextPath", contextPath);
        return "panel";
    }

    /**
     * 查询展示
     *
     * @param panelGroupDTO
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public Result showList(@RequestBody PanelGroupDTO panelGroupDTO) {
        Result result = Result.ok();
        try {
            QueryWrapper<PanelGroupDO> queryWrapper = new QueryWrapper();
            if (StringUtils.isNotBlank(panelGroupDTO.getGroupName())) {
                queryWrapper.like("group_name", panelGroupDTO.getGroupName());
            }
            queryWrapper.orderByDesc("create_time");
            Page<PanelGroupDO> page = panelGroupService.page(PageFactory.createPageInfo(panelGroupDTO.getCurrent(), panelGroupDTO.getSize()), queryWrapper);
            result.setData(page);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }


    /**
     * 批量删除 用户大屏组
     *
     * @param groupId
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestBody List<Integer> groupId) {
        Result result = Result.ok();
        try {
            if (groupId.size() > 0) {
                for (Integer id : groupId) {
                    PanelGroupDO oldPanelGroupDO = panelGroupService.getById(id);
                    SysFileDO oldPanelGroupFile = sysFileService.getById(oldPanelGroupDO.getFileId());
                    //移除PanelGroup 产生的文件信息
                    Integer countPanelGroup = sysFileService.removeByFileId(oldPanelGroupFile.getFileId());
                    if (countPanelGroup.intValue() > 0) {
                        //删除文件
                        FileUtil.deleteFile(oldPanelGroupFile);
                    }
                    //移除外表信息
                    QueryWrapper<PanelDO> panelDOQueryWrapper = new QueryWrapper<>();
                    panelDOQueryWrapper.eq("panel_group_id", oldPanelGroupDO.getGroupId());
                    List<PanelDO> panelDOList = panelService.list(panelDOQueryWrapper);
                    if (panelDOList.size() < 0) {
                        return Result.error("数据不存在");
                    }
                    for (PanelDO panelDO : panelDOList) {
                        //移除封面文件信息
                        SysFileDO panelFile = sysFileService.getById(panelDO.getFileId());
                        if (panelFile != null) {
                            Integer countPanelFile = sysFileService.removeByFileId(panelFile.getFileId());
                            if (countPanelFile.intValue() > 0) {
                                FileUtil.deleteFile(panelFile);
                            }
                        }
                        //删除背景图片信息
                        SysFileDO oldBackImg = sysFileService.getById(panelDO.getBackgroundId());
                        if (oldBackImg != null) {
                            Integer countOldBackImg = sysFileService.removeByFileId(oldBackImg.getFileId());
                            if (countOldBackImg.intValue() > 0) {
                                FileUtil.deleteFile(oldBackImg);
                            }
                        }
                        panelService.removeByPanelId(panelDO.getPanelId());
                    }
                }
                panelGroupService.removeByGroupIds(groupId);
            } else {
                return Result.error("不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 保存上传数据
     *
     * @param
     * @return
     */
    @PostMapping("/uploadData")
    @ResponseBody
    public Result uploadData(String operation, PanelGroupDO panelGroupDO) {
        Result result = Result.ok();
        try {
            StringBuffer data = new StringBuffer();
            data.append("上传成功。\n");

            //依据 fileId 查询出信息
            SysFileDO oldFile = sysFileService.getById(panelGroupDO.getFileId());
            if (oldFile == null) {
                result = Result.error("该数据不存在");
                return result;
            }

            if ("insert".equals(operation)) {
                //数据大屏组表
                panelGroupDO.setFileUrl(oldFile.getFileUrl());
                panelGroupService.savePanelGroup(panelGroupDO);
            } else {
                //修改  PanelGroupDO 表的信息
                PanelGroupDO oldPanelGroup = panelGroupService.getById(panelGroupDO.getGroupId());
                oldPanelGroup.setGroupName(panelGroupDO.getGroupName());
                oldPanelGroup.setFileUrl(oldFile.getFileUrl());
                oldPanelGroup.setUpdateTime(LocalDateTime.now());
                panelGroupService.saveOrUpdatePanelGroup(oldPanelGroup);
            }
            result.setData(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误,请重新上传");
        }
        return result;
    }

    /**
     * 查看 组 详细展示
     *
     * @param
     * @return
     */
    @PostMapping("/query")
    @ResponseBody
    public Result query(@RequestBody PanelDTO panelDTO) {
        Result result = Result.ok();
        try {
            QueryWrapper<PanelDO> queryWrapper = new QueryWrapper();
            queryWrapper.eq("panel_group_id", panelDTO.getPanelGroupId());
            if (StringUtils.isNotBlank(panelDTO.getPanelName())) {
                queryWrapper.like("panel_name", panelDTO.getPanelName());
            }
            Page<PanelDO> page = panelService.page(PageFactory.createPageInfo(panelDTO.getCurrent(), panelDTO.getSize()), queryWrapper);
            result.setData(page);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 上传图片 组 数据
     *
     * @param
     * @return
     */
    @PostMapping("/uploadPanelData")
    @ResponseBody
    public Result uploadPanelData(PanelDO panelDO, String operation) {
        Result result = Result.ok();
        try {
            StringBuffer data = new StringBuffer();
            data.append("上传成功。\n");

            //依据 fileId 查询出信息
            SysFileDO oldFile = sysFileService.getById(panelDO.getFileId());
            if (oldFile == null) {
                result = Result.error("该数据不存在");
                return result;
            }

            if ("insert".equals(operation)) {
                //把file_id和状态存入 大屏元素表
                PanelDO newPanelDO = new PanelDO();
                newPanelDO.setPanelGroupId(panelDO.getPanelGroupId());
                newPanelDO.setFileUrl(oldFile.getFileUrl());
                newPanelDO.setFileId(oldFile.getFileId());
                newPanelDO.setPanelName(panelDO.getPanelName());
                panelService.savePanel(newPanelDO);
            } else {
                //修改 PanelDO 表的信息
                PanelDO oldPanelDO = panelService.getById(panelDO.getPanelId());
                oldPanelDO.setPanelName(panelDO.getPanelName());
                oldPanelDO.setFileUrl(oldFile.getFileUrl());
                panelService.updatePanel(oldPanelDO);
            }
            result.setData(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误,请重新上传");
        }
        return result;
    }

    /**
     * 删除大屏
     *
     * @param panelId
     * @return
     */
    @PostMapping("/deletePanel")
    @ResponseBody
    public Result deletePanel(String panelId) {
        Result result = Result.ok();
        try {
            if (panelId != null) {
                //删除文件 先查出 fileId
                PanelDO oldPanel = panelService.getById(panelId);
                if (oldPanel != null) {
                    //封面文件
                    SysFileDO fileDO = sysFileService.getById(oldPanel.getFileId());
                    //前台的背景图片
                    SysFileDO oldBackgroundImg = sysFileService.getById(oldPanel.getBackgroundId());

                    panelService.removeByPanelId(oldPanel.getPanelId());
                    Integer countFile = sysFileService.removeByFileId(fileDO.getFileId());
                    Integer countBackgroundImg = sysFileService.removeByFileId(oldBackgroundImg.getFileId());

                    if (countFile.intValue() > 0) {
                        FileUtil.deleteFile(fileDO);
                    }

                    if (countBackgroundImg.intValue() > 0) {
                        FileUtil.deleteFile(fileDO);
                    }
                }
            } else {
                return Result.error("不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 前台查询展示
     *
     * @param panelGroupDTO
     * @return
     */
    @PostMapping("/queryAll")
    @ResponseBody
    public Result queryAll(PanelGroupDTO panelGroupDTO) {
        Result result = Result.ok();
        try {
            QueryWrapper<PanelGroupDO> queryWrapper = new QueryWrapper();
            if (StringUtils.isNotBlank(panelGroupDTO.getGroupName())) {
                queryWrapper.like("group_name", panelGroupDTO.getGroupName());
            }
            queryWrapper.orderByDesc("create_time");
            List<PanelGroupDO> listPanelGroup = panelGroupService.list(queryWrapper);
            result.setData(listPanelGroup);

        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 前台创建 panelGroup
     *
     * @param panelGroupDO
     * @return
     */
    @PostMapping("/insert")
    @ResponseBody
    public Result insert(PanelGroupDO panelGroupDO) {
        Result result = Result.ok();
        try {
            if (panelGroupDO != null) {
                //创建一个大屏
                long timeMillis = System.currentTimeMillis();
                SysFileDO oldFile = sysFileService.getById(panelGroupDO.getFileId());
                if (oldFile != null) {
                    panelGroupDO.setFileUrl(oldFile.getFileUrl());
                    panelGroupService.savePanelGroup(panelGroupDO);
                    PanelDO panelDO = new PanelDO();
                    panelDO.setPanelGroupId(panelGroupDO.getGroupId());
                    panelDO.setPanelName(panelGroupDO.getGroupName() + timeMillis);
                    panelService.savePanel(panelDO);
                }
            } else {
                return Result.error("不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 前台查询 panel展示
     *
     * @param panelDO
     * @return
     */
    @PostMapping("/queryPanel")
    @ResponseBody
    public Result queryPanel(PanelDO panelDO) {
        Result result = Result.ok();
        try {
            QueryWrapper<PanelDO> queryWrapper = new QueryWrapper();
            if (panelDO.getPanelGroupId() != null) {
                queryWrapper.eq("panel_group_id", panelDO.getPanelGroupId());
            }
            if (panelDO.getPanelId() != null) {
                queryWrapper.eq("panel_id", panelDO.getPanelId());
            }
            List<PanelDO> listPanel = panelService.list(queryWrapper);
            for (PanelDO panel : listPanel) {
                QueryWrapper<PanelModuleDO> panelModuleDOQueryWrapper = new QueryWrapper<>();
                panelModuleDOQueryWrapper.eq("panel_id", panel.getPanelId());
                List<PanelModuleDO> listPanelModule = panelModuleService.list(panelModuleDOQueryWrapper);
                panel.setChildren(listPanelModule);
            }
            result.setData(listPanel);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 前台删除 大屏组
     *
     * @param groupId
     */
    @PostMapping("/deletePanelGroup")
    @ResponseBody
    public Result deletePanelGroup(String groupId) {
        Result result = Result.ok();
        try {
            //首先查询关联的大屏表 和 module 表
            QueryWrapper<PanelDO> queryPanel = new QueryWrapper<>();
            queryPanel.eq("panel_group_id", groupId);
            List<PanelDO> listPanel = panelService.list(queryPanel);
            if (listPanel.size() > 0) {
                for (PanelDO panel : listPanel) {
                    QueryWrapper<PanelModuleDO> queryPanelModule = new QueryWrapper<>();
                    queryPanelModule.eq("panel_id", panel.getPanelId());
                    List<PanelModuleDO> listPanelModule = panelModuleService.list(queryPanelModule);
                    if (listPanelModule.size() > 0) {
                        for (PanelModuleDO panelModule : listPanelModule) {
                            panelModuleService.removeByModuleId(panelModule.getModuleId());
                        }
                    }
                    //移除大屏信息
                    panelService.removeByPanelId(panel.getPanelId());
                    SysFileDO oldSysFile = sysFileService.getById(panel.getFileId());
                    if (oldSysFile != null) {
                        Integer count = sysFileService.removeByFileId(oldSysFile.getFileId());
                        if (count.intValue() > 0) {
                            FileUtil.deleteFile(oldSysFile);
                        }
                    }
                }
            }
            //移除大屏组信息
            panelGroupService.removeByGroupId(Integer.valueOf(groupId));
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 前台保存大屏组
     *
     * @param jsonString
     */
    @PostMapping("/savePanelGroup")
    @ResponseBody
    public Result savePanelGroup(@RequestBody String jsonString) {
        Result result = Result.ok();
        try {
            String decode = URLUtil.decode(jsonString);
            JSONObject data = JSONUtil.parseObj(decode);
            JSONObject panels = data.getJSONObject("panels");
            JSONObject junks = data.getJSONObject("junks");
            if (panels != null) {
                for (String panel : panels.keySet()) {
                    JSONObject panelJson = panels.getJSONObject(panel);
                    Integer panelId = Integer.valueOf(panel);
                    String panelName = panelJson.getStr("name");
                    String showSrc = panelJson.getStr("showSrc");//封面的src
                    String panelOption = panelJson.getJSONObject("option").toJSONString(0);
                    //大屏自身的更改结束
                    //大屏只有修改 新增是实时写入的
                    PanelDO oldPanel = panelService.getById(panelId);
                    oldPanel.setPanelName(panelName);
                    oldPanel.setFileUrl(showSrc);
                    oldPanel.setConfigJson(panelOption);
                    panelService.updatePanel(oldPanel);

                    JSONObject modules = panelJson.getJSONObject("charts");
                    for (String moduleId : modules.keySet()) {
                        JSONObject module = modules.getJSONObject(moduleId);
                        String elementId = module.getStr("elementId");
                        String configJson = module.getJSONObject("option").toJSONString(0);
                        String offset = module.getJSONObject("offset").toJSONString(0);
                        String dataSrc = module.getJSONObject("dataSrc").toJSONString(0);
                        PanelModuleDO oldPanelModule = panelModuleService.getById(moduleId);
                        if (oldPanelModule == null) {
                            //新增
                            PanelModuleDO newPanelModule = new PanelModuleDO();
                            newPanelModule.setModuleId(moduleId);
                            newPanelModule.setElementId(Integer.valueOf(elementId));
                            newPanelModule.setConfigJson(configJson);
                            newPanelModule.setDataSource(dataSrc);
                            newPanelModule.setModuleJson(offset);
                            newPanelModule.setPanelId(panelId);
                            panelModuleService.savePanelModule(newPanelModule);
                        } else {
                            //修改
                            oldPanelModule.setConfigJson(configJson);
                            oldPanelModule.setModuleJson(offset);
                            oldPanelModule.setDataSource(dataSrc);
                            panelModuleService.updateById(oldPanelModule);
                        }
                    }
                }
            }

            JSONArray chartIds = junks.getJSONArray("chart");
            if (chartIds != null) {
                for (Object chartId : chartIds) {
                    String id = chartId.toString();
                    //通过id删除module
                    panelModuleService.removeByModuleId(id);
                }
            }
            JSONArray fileIds = junks.getJSONArray("file");
            if (fileIds != null) {
                for (Object fileId : fileIds) {
                    String id = fileId.toString();
                    SysFileDO file = sysFileService.getById(id);
                    Integer integer = sysFileService.removeByFileId(file.getFileId());
                    if (integer.intValue() > 0) {
                        FileUtil.deleteFile(file);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误");
        }
        return result;
    }

    /**
     * 前台上传大屏图片
     *
     * @param panelId
     */
    @PostMapping("/uploadAndSavePanel")
    @ResponseBody
    public Result uploadAndSavePanel(@RequestParam("file") MultipartFile[] files, String panelId, String imgType) {
        Result result = Result.ok();
        try {
            if (files.length == 0) {
                result = Result.error("文件不能为空");
                return result;
            }

            Map<String, String> resultMap = FileUtil.upload(files[0], basePath);
            SysFileDO sysFileDO = new SysFileDO();
            sysFileDO.setFileId(IdUtil.simpleUUID());
            sysFileDO.setFileName(resultMap.get("oldName"));
            sysFileDO.setFilePath(resultMap.get("path"));
            sysFileDO.setFileUrl("upload/" + resultMap.get("newName"));
            sysFileService.saveSysFile(sysFileDO);

            //存入 大屏表
            PanelDO oldPanel = panelService.getById(panelId);
            if (oldPanel != null) {
                //0为背景，1为封面
                if ("0".equals(imgType)) {
                    //删除旧的背景图片信息
                    if (oldPanel.getBackgroundId() != null) {
                        SysFileDO oldBackgroundFile = sysFileService.getById(oldPanel.getBackgroundId());
                        if (oldBackgroundFile != null) {
                            Integer count = sysFileService.removeByFileId(oldBackgroundFile.getFileId());
                            if (count.intValue() > 0) {
                                FileUtil.deleteFile(oldBackgroundFile);
                            }
                        }
                    }
                    oldPanel.setBackgroundId(sysFileDO.getFileId());
                    oldPanel.setBackgroundUrl(sysFileDO.getFileUrl());
                } else {
                    //删除旧的封面文件信息
                    if (oldPanel.getFileId() != null) {
                        SysFileDO oldSysFile = sysFileService.getById(oldPanel.getFileId());
                        if (oldSysFile != null) {
                            FileUtil.deleteFile(oldSysFile);
                            sysFileService.removeByFileId(oldSysFile.getFileId());
                        }
                    }
                    oldPanel.setFileId(sysFileDO.getFileId());
                    oldPanel.setFileUrl(sysFileDO.getFileUrl());
                }
                panelService.updatePanel(oldPanel);
            } else {
                result = Result.error("大屏不存在");
                return result;
            }
            result.setData(oldPanel);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 前台 删除大屏信息
     *
     * @param panelId
     */
    @PostMapping("/deletePanelAndImage")
    @ResponseBody
    public Result deletePanelAndImage(String panelId) {
        Result result = Result.ok();
        try {
            if (!"".equals(panelId) || panelId.length() > 0) {
                //删除对应的保存module 信息
                QueryWrapper<PanelModuleDO> queryPanelModuel = new QueryWrapper<>();
                queryPanelModuel.eq("panel_id", panelId);
                List<PanelModuleDO> oldPanelModuleList = panelModuleService.list(queryPanelModuel);
                for (PanelModuleDO panelModule : oldPanelModuleList) {
                    panelModuleService.removeByModuleId(panelModule.getModuleId());
                }

                //删除封面文件信息
                PanelDO oldPanel = panelService.getById(panelId);
                if (oldPanel.getFileId() != null) {
                    SysFileDO oldSysFile = sysFileService.getById(oldPanel.getFileId());
                    if (oldSysFile != null) {
                        Integer count = sysFileService.removeByFileId(oldSysFile.getFileId());
                        if (count.intValue() > 0) {
                            FileUtil.deleteFile(oldSysFile);
                        }
                    }
                }

                //删除背景图片信息
                if (oldPanel.getBackgroundId() != null) {
                    SysFileDO oldBackImg = sysFileService.getById(oldPanel.getBackgroundId());
                    if (oldBackImg != null) {
                        Integer count = sysFileService.removeByFileId(oldBackImg.getFileId());
                        if (count.intValue() > 0) {
                            FileUtil.deleteFile(oldBackImg);
                        }
                    }
                }

                panelService.removeByPanelId(Integer.valueOf(panelId));
            } else {
                return Result.error("前台传入参数不能为空");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 前台 删除已保存的 module 信息
     *
     * @param panelId
     */
    @PostMapping("/deletePanelModule")
    @ResponseBody
    public Result deletePanelModule(String panelId) {
        Result result = Result.ok();
        try {
            if (!"".equals(panelId) || panelId.length() > 0) {
                //删除对应的保存module 信息
                QueryWrapper<PanelModuleDO> queryPanelModuel = new QueryWrapper<>();
                queryPanelModuel.eq("panel_id", panelId);
                List<PanelModuleDO> oldPanelModuleList = panelModuleService.list(queryPanelModuel);
                for (PanelModuleDO panelModule : oldPanelModuleList) {
                    panelModuleService.removeByModuleId(panelModule.getModuleId());
                }
            } else {
                return Result.error("前台传入参数不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 前台 新增一个大屏
     *
     * @param groupId
     */
    @PostMapping("/insertPanel")
    @ResponseBody
    public Result insertPanel(String groupId) {
        Result result = Result.ok();
        try {
            if (groupId != null) {
                long timeMillis = System.currentTimeMillis();
                PanelDO panelDO = new PanelDO();
                panelDO.setPanelName("大屏" + timeMillis);
                panelDO.setPanelGroupId(Integer.valueOf(groupId));
                panelService.savePanel(panelDO);
                result.setData(panelDO);
            } else {
                return Result.error("前台传入groupId为空！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
